package cn.jja8.config.tool.work;

import cn.jja8.config.tool.work.basic.BasicFieldHandManager;
import cn.jja8.config.tool.work.obj.ObjKeepManager;

import java.lang.reflect.Field;

public class FieldAsManager {
    private final BasicFieldHandManager basicFieldHandManager = new BasicFieldHandManager();
    private final ObjKeepManager objKeepManager = new ObjKeepManager();

    public BasicFieldHandManager getBasicFieldHandManager() {
        return basicFieldHandManager;
    }
    public ObjKeepManager getObjKeepManager() {
        return objKeepManager;
    }

    /**
     * 将con还原后写人到ojg的field字段
     * */
    public void read(Field field, Object obj, Object con) throws Throwable {
        field.setAccessible(true);
        Class fieldClass = field.getType();
        //如果是基础类型
        if (fieldClass.isPrimitive()){
            basicFieldHandManager.getNoNull(fieldClass).setValue(field,obj,con);
            return;
        }
        //如果class是obj
        field.set(obj,objKeepManager.in(con,field.getGenericType()));
    }

    /**
     * 将obj的field字段取出并格式化
     * */
    public Object write(Field field, Object obj) throws Throwable {
        field.setAccessible(true);
        Class fieldClass = field.getType();
        //如果是基础类型
        if (fieldClass.isPrimitive()){
            return basicFieldHandManager.getNoNull(fieldClass).getValue(field,obj);
        }
        //如果class是obj
        return objKeepManager.out(field.get(obj),field.getGenericType());
    }
}
